﻿using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Diagnostics;
using System.Xml.Linq;
using Microsoft.Office.Tools.Word;
using Microsoft.VisualStudio.Tools.Applications.Runtime;
using eRechnung.ExtensionMethods;
using eRechnung.Version;
using Office = Microsoft.Office.Core;
using Tools = Microsoft.Office.Tools;
using Word = Microsoft.Office.Interop.Word;
using eRechnung.Properties;
using System;
using System.Data;
using System.IO;


namespace eRechnung
{
   
    // Debugging Hilfen / Symbole
    //
    //  SAVE_HTML generiert Code zum Speichern den HTML Seiten der Handy Signatur
    //  TEST_A_TRUST Generiert Code zum Testen über die A-Trust Test Seite


    public partial class ThisDocument
    {

        public ebInterfaceTableManager XlateTables;
        public InvoiceXSD InvXSD;
        [Cached()]
        public string InvoiceXMLPartID;
        public Office.CustomXMLPart InvoiceXMLPart;
        public InvoiceXML InvXml = new InvoiceXML();
        private object pwd = "AustriaPro";
        public decimal BetragExklMwSt = 0;
        public decimal BetragInklMwSt = 0;
        public decimal BetragMwSt = 0;
        public DateTime Rechnungsdatum = DateTime.Today;
        public DateTime RechnungsdatumInTemplate = DateTime.Today;
        public DateTime FaelligDatum = DateTime.Today;
        public bool DatumHasChanged = false;
        private bool DocIsBeeingSaved = false;
        private bool DocIsProtected = false;
        // public ebI_Ribbon ebIRibbon = new ebI_Ribbon();

        #region Details
        // Tabellenkopf
        //1 Pos.
        //2 ArtikelNr	
        //3 Bezeichnung	
        //4 Menge	
        //5 Einheit	
        //6 Einzelpreis	
        //7 Rabatt%	
        //8 MwSt%	
        //9 Gesamtbetrag 

        // Tabelle die die Spalten in Word Tabelle und DataSet-Table mapped
        // die Columnnamen sind in der Reihenfolge der Spalten im Word Dok geordnet
        // ACHTUNG: die erste Spalte ist die Positionsnummer
        private string[] dtDetailsColName = {
#if ebInterface4Bund
                                  "SpBestellBezug", // -> pos 2!
#endif
                                  "spArtikelNr",    
                                  "spBezeichnung",  
                                  "spMenge",
                                  "SpEinheit",
                                  "spEinzelPreis",
                                  "spRabattProz",
                                  "spMwst",
                                  "spGesamtBetrag"};

        private string[] dtDetailsColFmt = {
#if ebInterface4Bund
                                  "",    // -> pos 2!
#endif
                                  "",  
                                  "",  
                                  "#,##0.00",
                                  "",
                                  "#,##0.00",
                                  "0.00%",
                                  "c0.00%",
                                  "#,##0.00"};

        #endregion
        #region MwST
        // Mehrwertsteuertabelle
        //1 MwSt %	
        //2 Basisbetrag	
        //3 MwSt Betrag	
        //4 Gesamtbetrag

        private string[] dtMwStColName = {"spMwSt", 
                                          "spBasisBetrag",
                                          "spMwStBetrag",
                                          "spGesamtBetrag"
                                         };
        private string[] dtMwStColFmt ={"0.00%",
                                        "#,##0.00",
                                        "#,##0.00",
                                        "#,##0.00"};

        #endregion
        #region Skonto
        // Skontotabelle
        //1 Bis Datum	Nimmermehr
        //2 Tage
        //3 Skonto%	
        //4 BasisBetrag
        //3 Skonto Betrag

        //private string[] dtSkontoColName = { "SpBisDatum", "SpTage", "SpSkontoProz", "spBasisBetrag", "spSkontoBetrag" };
        //private string[] dtSkontoColFmt = { "dd", "0", "0.00%", "#,##0.00", "#,##0.00" };

        private string[] dtSkontoColName = {  "SpTage", "SpSkontoProz", "spBasisBetrag", "spSkontoBetrag" };
        private string[] dtSkontoColFmt = { "0", "0.00%", "#,##0.00", "#,##0.00" };

        #endregion
        private const int docDetailsTab = 2;    // Nummer der Detailstabelle im Word Dokument
        private const int docMwstTab = 3;       // NUmmer der Mehrwehrtsteuertabelle im Dokument
        private const int docSkontoTab = 4;     // Nummer der Skontotabelle

        private const string nbsp = "\u00A0";

        private string[] ReText1 = { "Rechnungsbetrag exkl. MwSt", "Rechnungsbetrag" };
        private string[] ReText2 = { "Summe MwSt", "Summe MwSt" };
        private string[] ReText3 = { "Rechnungsbetrag inkl. MwSt", "Gesamt" };

        private string[] excludeFromHide = new string[] { "CC_ReText1", "CC_ReText2", "CC_ReText3" };

        #region Startup und Shutdown Funktionen
        private void MyThisDocument_Startup(object sender, System.EventArgs e)
        {
            Globals.Ribbons.ebI_Ribbon.SetRibbonButtonsEnable(false);      // Ribbon disabled
            Word.Document doc = eRechnung.Globals.ThisDocument.Application.ActiveDocument;

            XlateTables = new ebInterfaceTableManager();
            InvXSD = new InvoiceXSD();
            // MessageBox.Show("Protection=" + doc.ProtectionType.ToString());
            if (doc.ProtectionType != Word.WdProtectionType.wdNoProtection)
            {
                UnprotectDoc("ThisDocument");
                
            }
            HidePlaceHolder();
            string xmldata = GetFromXMLResource(InvoiceXML.ebInterfaceLeer);
            if (InvoiceXMLPart!=null)
            {
                MessageBox.Show("PartID = " + InvoiceXMLPart);
            }
            if (CC_InternalID.ShowingPlaceholderText != true)
            {
                InvoiceXMLPartID = CC_InternalID.Text;
            }
            LoadXML2CustomPart(xmldata);       // Laden der XML Daten
            ProtectDoc("ThisDocument_Startup");
            UpdateDocDetails();     // muss nach ProtectDoc() stehen, da das doc temp wieder unprotected wird
            
        }

        private void MyThisDocument_Shutdown(object sender, System.EventArgs e)
        {

        }

        //protected override Microsoft.Office.Core.IRibbonExtensibility CreateRibbonExtensibilityObject()
        //{
        //    return new eRechung_Ribbon();
        //}
        #endregion

        #region Dokumentenbehandlung


        private void HidePlaceHolder()
        {
            //UnprotectDoc("HideHeader");
            Word.Document doc = eRechnung.Globals.ThisDocument.Application.ActiveDocument;

            foreach (Word.ContentControl ctrl in doc.ContentControls)
            {
                HideContentControl(ctrl, true);
            }

            HideContentControl(CC_Headline.InnerObject, true);


            CC_Fehlerliste.LockContents = false;
            CC_InternalID.LockContents = false;
            foreach (Word.Bookmark bkmk in doc.Bookmarks)
            {
                if (!bkmk.Name.StartsWith("DoNotHide"))
                {
                    bkmk.Range.Font.Hidden = 1;
                }
            }
            CC_Fehlerliste.LockContents = true;
            CC_InternalID.LockContents = true;
            //ProtectDoc("HideHeader");
        }

        public void HideContentControl(Word.ContentControl ctrl, bool hide)
        {
            bool LockCC = ctrl.LockContentControl;
            bool LockContent = ctrl.LockContents;
            if (LockCC || LockContent)
            {
                ctrl.LockContentControl = false;
                ctrl.LockContents = false;
            }
            ctrl.Range.Font.Hidden = hide == true ? 1 : 0;


            ctrl.LockContentControl = LockCC;
            ctrl.LockContents = LockContent;

        }


        public void SetFehlerText(string text)
        {
            CC_Fehlerliste.LockContents = false;
            CC_Fehlerliste.Text = text;
            CC_Fehlerliste.LockContents = true;
        }

        public void SetCustomXMLID(string text)
        {
            CC_InternalID.LockContents = false;
            CC_InternalID.Text = text;
            CC_InternalID.LockContents = true;
        }
       
        public void Settings2Doc(DsInvoice myDs)
        {
            this.CC_BillerName.Text = Settings.Default.setName;
            this.CC_BillerStreet.Text = Settings.Default.setStrasse;
            this.CC_BillerTown.Text = Settings.Default.setOrt;
            this.CC_BillerZip.Text = Settings.Default.setPLZ;
            SelectDropDownValue(this.CC_BillerCountry.DropDownListEntries, Settings.Default.setLand);
            this.CC_BillerPhone.Text = Settings.Default.setTelNr;
            this.CC_BillerEmail.Text = Settings.Default.setEmail;
            this.CC_BillerVATID.Text = Settings.Default.setVATID;
            this.CC_BillerContact.Text = Settings.Default.setBillerContact;

            SelectDropDownValue(this.CC_Currency.DropDownListEntries, Settings.Default.setWhrg);

            SetVATTextInDoc();

            this.CC_BankName.Text = Settings.Default.setBank;

#if !ebInterface4Bund
            // this.CC_BankAccountNr.Text=Settings.Default.setKontonr;
            
#endif
            this.CC_BankAccountOwner.Text = Settings.Default.setKontowortlaut;
#if !ebInterface4Bund
            // this.CC_BankCode.Text=Settings.Default.setBLZ;
#endif
            this.CC_BankIBAN.Text = Settings.Default.setIBAN;
            this.CC_BankBIC.Text = Settings.Default.setBIC;

            // SelectDropDownValue(this.CC_BankCountry.DropDownListEntries, Settings.Default.setBankLand);
            if (myDs != null)
            {
                CopyTable(myDs, InvXml.InvDetails, myDs.TblMWST.TableName);
            }
            // this.CC_RecipientName.Range.Select();
            return;
        }

        public void SetVATTextInDoc()
        {
            if (Settings.Default.SetVStBerechtigt == true)
            {
                UpdateLockedCCText(CC_ReText1, ReText1[0]);
                UpdateLockedCCText(CC_ReText2, ReText2[0]);
                UpdateLockedCCText(CC_ReText3, ReText3[0]);
                //string betr;
                //betr = "";
                //if (CC_BetragExcl.ShowingPlaceholderText!=true)
                //{
                //    betr = CC_BetragExcl.Text;
                //}
                //UpdateLockedCCText(CC_Rechnungsbetrag, betr);
                //UpdateLockedCCText(CC_MwSt, "");
            }
            else
            {
                UpdateLockedCCText(CC_ReText1, ReText1[1]);
                UpdateLockedCCText(CC_ReText2, "Keine VSt Abzugsberechtigung: \"" + Settings.Default.SetVStText + "\" MwSt daher");
                UpdateLockedCCText(CC_ReText3, ReText3[1]);
                //UpdateLockedCCText(CC_Rechnungsbetrag, nbsp);
                //UpdateLockedCCText(CC_MwSt, nbsp);
            }
        }
        /// <summary>
        /// Initialisiert alle COntrols in der Vorlage und verbindet diese mit XML Tags
        /// </summary>
        private void InitDoc()
        {
            UnprotectDoc("InitDoc");
            try
            {
                MapPlainTextControl(this.CC_BillerName, InvoiceXML.xPathBillerName, Settings.Default.setName);
                MapPlainTextControl(this.CC_BillerStreet, InvoiceXML.xPathBillerStreet, Settings.Default.setStrasse);
                MapPlainTextControl(this.CC_BillerTown, InvoiceXML.xPathBillerTown, Settings.Default.setOrt);
                MapPlainTextControl(this.CC_BillerZip, InvoiceXML.xPathBillerZip, Settings.Default.setPLZ);
                FillCountry(this.CC_BillerCountry, InvoiceXML.xPathBillerCountry, Settings.Default.setLand);
                MapPlainTextControl(this.CC_BillerPhone, InvoiceXML.xPathBillerPhone, Settings.Default.setTelNr);
                MapPlainTextControl(this.CC_BillerEmail, InvoiceXML.xPathBillerEmail, Settings.Default.setEmail);
                MapPlainTextControl(this.CC_BillerVATID, InvoiceXML.xPathBillerVATID, Settings.Default.setVATID);
                MapPlainTextControl(this.CC_BillerContact, InvoiceXML.xPathBillerContact, Settings.Default.setBillerContact);
#if ebInterface4Bund
                // ToDo Setting für Lieferanten GLN einbauen
                MapPlainTextControl(this.CC_BillerGLNum, InvoiceXML.xPathBillerGlnId, "");
                // ToDo Setting für BillersID einbauen
                MapPlainTextControl(this.CC_BillersID, InvoiceXML.xPathBillerInvRecBillersID, "");
#endif

                MapPlainTextControl(this.CC_RecipientSalutation, InvoiceXML.xPathInvRecSalute, "");
                MapPlainTextControl(this.CC_RecipientName, InvoiceXML.xPathInvRecName, "");
                MapPlainTextControl(this.CC_RecipientStreet, InvoiceXML.xPathInvRecStreet, "");
                MapPlainTextControl(this.CC_RecipientTown, InvoiceXML.xPathInvRecTown, "");
                MapPlainTextControl(this.CC_RecipientZip, InvoiceXML.xPathInvRecZip, "");
                FillCountry(this.CC_RecipientCountry, InvoiceXML.xPathInvRecCountry, "Österreich");
                MapPlainTextControl(this.CC_RecipientPhone, InvoiceXML.xPathInvRecPhone, "");
                MapPlainTextControl(this.CC_RecipientEmail, InvoiceXML.xPathInvRecEmail, "");
#if ebInterface4Bund
                MapPlainTextControl(CC_ReceipientGLN, InvoiceXML.xPathInvRecGlnId, "");
#endif
                MapPlainTextControl(this.CC_AcctArea, InvoiceXML.xPathInvAcctArea, "");
                MapPlainTextControl(this.CC_SubOrgID, InvoiceXML.xPathInvSubOrgID, "");
                MapPlainTextControl(this.CC_RecipientVATID, InvoiceXML.xPathInvRecVATID, "00000000");

                MapPlainTextControl(this.CC_RecipientContact, InvoiceXML.xPathInvRecContact, "");

                FillDocumentType(this.CC_InvoiceType, InvoiceXML.xPathDocumentType, "Invoice");

                MapPlainTextControl(this.CC_BillersReceipientID, InvoiceXML.xPathInvRecBillerID, "");

                MapDateControl(this.CC_InvoiceDate, InvoiceXML.xPathInvDate, Rechnungsdatum.ToString("yyyy-MM-dd"));
                MapPlainTextControl(this.CC_InvoiceNumber, InvoiceXML.xPathInvNumber, "");

                MapPlainTextControl(this.CC_OrderReference, InvoiceXML.xPathOrderRefID, "");

                MapDateControl(this.CC_OrderDate, InvoiceXML.xPathOrderRefDate, "");

                MapDateControl(this.CC_DeliverydateStart, InvoiceXML.xPathDeliveryDate, Rechnungsdatum.ToString("yyyy-MM-dd"));

                FillCurrency(this.CC_Currency, InvoiceXML.xPathCurrency, Settings.Default.setWhrg);
                MapDateControl(this.CC_DueDate, InvoiceXML.xPathPaymtDuedate, Rechnungsdatum.ToString("yyyy-MM-dd"));

                MapPlainTextControl(this.CC_BankName, InvoiceXML.xPathBankName, Settings.Default.setBank);
#if !ebInterface4Bund
                // MapPlainTextControl(this.CC_BankAccountNr, InvoiceXML.xPathBankAcctNr, Settings.Default.setKontonr);

#endif
                MapPlainTextControl(this.CC_BankAccountOwner, InvoiceXML.xPathBankAcctOwner, Settings.Default.setKontowortlaut);
#if !ebInterface4Bund
                //MapPlainTextControl(this.CC_BankCode, InvoiceXML.xPathBankBLZ, Settings.Default.setBLZ);

#endif
                MapPlainTextControl(this.CC_BankIBAN, InvoiceXML.xPathBankIBAN, Settings.Default.setIBAN);
                MapPlainTextControl(this.CC_BankBIC, InvoiceXML.xPathBankBIC, Settings.Default.setBIC);
                MapPlainTextControl(this.CC_Referenz, InvoiceXML.xPathPaymtReferenz, "");

                // FillCountry(this.CC_BankCountry, InvoiceXML.xPathBankLand, Settings.Default.setBankLand);

                FillDocumentType(this.CC_InvoiceType, InvoiceXML.xPathDocumentType, "Invoice");
                // FillCountry(this.CC_BankCountry, InvoiceXML.xPathBankLand, Settings.Default.setBankLand);
                FillPlanTextCC(this.CC_DocumentTitle, InvoiceXML.xPathDocumentTitle, "Beispiel-Rechnung");

                MapPlainTextControl(CC_DetailsHeaderDescription, InvoiceXML.xPathDetailsHeader, "Wir erlauben uns wie folgt zu verrechnen");
                MapPlainTextControl(CC_DetailsFooter, InvoiceXML.xPathDetailsFooter, "Wir danken für Ihren Auftrag");


                MapPlainTextControl(this.CC_Rechnungsbetrag, InvoiceXML.xPathTotGrossAmount, "");
                SetVATTextInDoc();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                ProtectDoc("InitDoc-Exception");

                throw;
            }
            ProtectDoc("InitDoc");
        }
        /// <summary>
        /// Setzt 
        /// </summary>
        /// <param name="ctrl"></param>
        /// <param name="xPath"></param>
        /// <param name="setting"></param>
        private void FillPlanTextCC(Tools.Word.PlainTextContentControl ctrl,
                        string xPath,
                        string setting)
        {
            Office.CustomXMLNode vnode = InvoiceXMLPart.SelectSingleNode(xPath);
            if (vnode.Text == "")
            {
                vnode.Text = setting;
            }
            ctrl.Text = vnode.Text;
        }

        private void MapDateControl(Tools.Word.DatePickerContentControl ctrl,
                        string xPath,
                        string setting)
        {
            Office.CustomXMLNode vnode = InvoiceXMLPart.SelectSingleNode(xPath);
            if (vnode == null)
            {
                throw new MissingFieldException("Fehler beim Mapping.\r\n" + "xPath=" + xPath + "/r/nfür das Feld=" + ctrl.Title + "\r\nwurde nicht gefunden.\r\nBitte diesen Fehler im Forum auf http://ebinterface.codeplex.com berichten.");
            }
            if (vnode.Text == "")
            {
                vnode.Text = setting;
            }
            // ctrl.Tag = xPath;
            ctrl.XMLMapping.SetMapping(xPath, InvoiceXML.Prefix, InvoiceXMLPart);
        }
        /// <summary>
        /// Erstellt das Mapping zwischen Control im Dokument und XML
        /// </summary>
        /// <param name="ctrl">Word Control</param>
        /// <param name="xPath">xPath in XML</param>
        /// <param name="setting">Default Wert</param>
        private void MapPlainTextControl(Tools.Word.PlainTextContentControl ctrl,
                        string xPath,
                        string setting)
        {
            string XMLField = xPath;
            Office.CustomXMLNode vnode = InvoiceXMLPart.SelectSingleNode(XMLField);
            if (vnode == null)
            {
                throw new MissingFieldException("Fehler beim Mapping.\r\n" + "xPath=" + xPath + "\r\nfür das Feld=" + ctrl.Title + "\r\nwurde nicht gefunden.\r\nBitte diesen Fehler im Forum auf http://ebinterface.codeplex.com berichten.");
            }
            if (vnode.Text == "")
            {
                vnode.Text = setting;
            }
            // ctrl.Tag = xPath;
            ctrl.XMLMapping.SetMapping(XMLField, InvoiceXML.Prefix, InvoiceXMLPart);

        }
        /// <summary>
        /// Füllt ein DropDown Control
        /// </summary>
        /// <param name="ctrl"></param>
        /// <param name="values"></param>
        /// <param name="selection"></param>
        private void FillDropDownList(Tools.Word.DropDownListContentControl ctrl, string[] values, string selection)
        {
            ctrl.DropDownListEntries.Clear();
            int ictr = 0;
            foreach (string wert in values)
            {
                ctrl.DropDownListEntries.Add(wert, wert, ictr);
                ictr++;
            }

            SelectDropDownValue(ctrl.DropDownListEntries, selection);
        }
        /// <summary>
        /// Füllt das Währungscontrol
        /// </summary>
        /// <param name="ctrl"></param>
        /// <param name="xPath"></param>
        /// <param name="defVal"></param>
        private void FillCurrency(Tools.Word.DropDownListContentControl ctrl, string xPath, string defVal)
        {
            string[] docType = InvXSD.GetAllCurrencies();
            Office.CustomXMLNode vnode = InvoiceXMLPart.SelectSingleNode(xPath);
            string sel = defVal;
            if (vnode != null)
            {
                sel = vnode.Text;
            }

            FillDropDownList(ctrl, docType, sel);

        }
        /// <summary>
        /// Füllt den Dokumententyp auf Deutsch
        /// </summary>
        /// <param name="ctrl"></param>
        /// <param name="xPath"></param>
        /// <param name="defVal"></param>
        private void FillDocumentType(Tools.Word.DropDownListContentControl ctrl, string xPath, string defVal)
        {
            // string[] docType = InvXSD.GetAllInvoiceTypes();
            string[] docType = XlateTables.GetAllGerDocTypes();
            Office.CustomXMLNode vnode = InvoiceXMLPart.SelectSingleNode(xPath);
            string sel = defVal;
            if (vnode != null)
            {
                sel = vnode.Text;
            }

            FillDropDownList(ctrl, docType, XlateTables.FindDocTypeGerman(sel));

        }
        /// <summary>
        /// Füllt das Land und übersetzt dabei zwischen Langtext und Abkürzung
        /// </summary>
        /// <param name="ctrl"></param>
        /// <param name="xPath"></param>
        /// <param name="defVal"></param>
        private void FillCountry(Tools.Word.DropDownListContentControl ctrl, string xPath, string defVal)
        {
            String[] Countries = XlateTables.GetAllCountries();
            // Aktuellen Wert wählen
            Office.CustomXMLNode vnode = InvoiceXMLPart.SelectSingleNode(xPath);

            // defVal = "" -> keine Defaultwerte
            string sel = XlateTables.FindShortcut(defVal);

            if (vnode.Text != "")
            {
                sel = vnode.Text;
            }
            string selection = defVal;

            //if (sel != "")
            //{
            //    selection = XlateTables.FindLand(sel);
            //}
            FillDropDownList(ctrl, Countries, selection);

        }
        /// <summary>
        /// Selektiert einen Wert in der ContentControlList
        /// </summary>
        /// <param name="myLe"></param>
        /// <param name="wert"></param>
        private void SelectDropDownValue(Word.ContentControlListEntries myLe, string wert)
        {
            foreach (Word.ContentControlListEntry myEntry in myLe)
            {
                if (myEntry.Value == wert)
                {
                    myEntry.Select();
                }
            }
        }
        #endregion


        #region Hilfsfunktionen

        /// <summary>
        /// ebInterface Dokument schützen
        /// </summary>
        public void ProtectDoc(string caller)
        {
            object UseIRM = false;
            object noreset = false;
            LogLine("Protect at Entry: " + this.ProtectionType.ToString()+ ", Caller: "+ caller);
            if (this.ProtectionType != Word.WdProtectionType.wdNoProtection)
            {
                return;
            }

            this.Protect(
                Microsoft.Office.Interop.Word.WdProtectionType.wdAllowOnlyFormFields,
                ref noreset,
                ref pwd,
                ref UseIRM,
                ref missing);
            
            // AppExtensions.eProtectDoc("ProtectDoc:" + caller, ThisApplication.ActiveDocument, true);
            DocIsProtected = true;

        }




        /// <summary>
        /// ebInterface Dokumentenschutz aufheben
        /// </summary>
        public void UnprotectDoc(string caller)
        {
            LogLine("Unprotect at Entry: " + this.ProtectionType.ToString() + ", Caller: " + caller);
            object nopwd = "";
            if (this.ProtectionType == Word.WdProtectionType.wdNoProtection)
            {
                return;
            }
            this.Unprotect(ref pwd);
            //AppExtensions.eProtectDoc("UnprotectDoc" + ":" + caller, ThisApplication.ActiveDocument, false);
            DocIsProtected = false;
        }

        public void LoadXML2CustomPart(string xmldata)
        {

            InvoiceXMLPart = InvXml.AddCustomXmlPart(xmldata);
            InvXml.InvDetails.LoadMwStTab();
            bool retVal = InvXml.LoadDetailsTable(InvoiceXMLPart, InvXml.InvDetails);
            InitDoc();
            InvXml.LoadSkontoTable(InvoiceXMLPart, InvXml.InvDetails); // Muss nach InitDoc liegen damit auf die ContentControls zugegriffen werden kann
        }

        /// <summary>
        /// Formattiert einen string als Datum, decimal oder Prozent für die Anzeige im Word ebDoc
        /// </summary>
        /// <param name="Format">Format Angabe entstprechend string.Format</param>
        /// <param name="wert">Datenwert</param>
        /// <returns></returns>
        private string FormatDecimal(string Format, string wert)
        {
            string retval = string.Empty;
            string form = Format;
            if (form.StartsWith("d"))
            {
                DateTime val;
                if (wert != null)
                {
                    val = DateTime.Parse(wert);
                    form = form.Substring(1, form.Length - 1);
                    retval = val.ToString(form); //, System.Globalization.CultureInfo.InvariantCulture);
                }
            }
            else
            {
                decimal val = 0;
                if (wert != "")
                {
                    val = decimal.Parse(wert);
                    if (form.StartsWith("c"))
                    {
                        form = form.Substring(1); // c entfernen.

                        if (form.EndsWith("%") && (val == -1))
                        {
                            return ("");
                        }
                    }
                }
                else
                {
                    val = 0;
                }
                if (form.EndsWith("%") == true)
                {
                    val /= 100;         // Prozentwert
                }
                retval = val.ToString(form); //, System.Globalization.CultureInfo.InvariantCulture);

            }

            return (retval);
        }
        /// <summary>
        /// Kopiert die angegebene Tabelle von einem DAtaset in das andere
        /// </summary>
        /// <param name="vonDs">von Dataset</param>
        /// <param name="nachDs">nach Dataset</param>
        /// <param name="tabName">Name der Tabelle</param>
        public void CopyTable(DsInvoice vonDs, DsInvoice nachDs, string tabName)
        {
            DataTable von = vonDs.Tables[tabName];
            DataTable nach = nachDs.Tables[tabName];
            nach.Clear();
            foreach (DataRow Row in von.Rows)
            {
                nach.Rows.Add(Row.ItemArray); // Zeile kopieren
            }
        }
        /// <summary>
        /// Skontotabelle aus dem Form zurück in die eigene Tab kopieren
        /// und das ebDoc updaten
        /// </summary>
        /// <param name="myDs"></param>
        public void SaveSkonto(DsInvoice myDs)
        {
            CopyTable(myDs, InvXml.InvDetails, myDs.TblInvSkonto.TableName);
            // UpdateDocDetails();
            FillSkontoTabInDoc();
        }
        /// <summary>
        /// Details aus dem Form in die eigne Tab kopieren 
        /// und das ebDoc updaten
        /// </summary>
        /// <param name="myDs"></param>
        public void SaveDetails(DsInvoice myDs)
        {
            CopyTable(myDs, InvXml.InvDetails, myDs.TblInvDetails.TableName);
            UpdateDocDetails();
        }
        /// <summary>
        /// MWST Summentabelle aufbauen
        /// </summary>
        private void FillMwStTabInDoc()
        {
            // 1. Summen berechnen
            InvXml.InvDetails.TblMwStSummen.Clear(); // alle Daten löschen
            System.Nullable<Decimal> SummeExklMwSt = 0;
            System.Nullable<Decimal> SummeInklMwSt = 0;
            System.Nullable<Decimal> SummeMwSt = 0;
            decimal mwst = 0;
            DsInvoice.TblMwStSummenRow mwstRow = null;
            BetragExklMwSt = 0;
            BetragInklMwSt = 0;
            BetragMwSt = 0;

            foreach (DsInvoice.TblMWSTRow rMWST in InvXml.InvDetails.TblMWST)
            {
                mwst = rMWST.SpMwSt;
                if (mwst >= 0)
                {
                    SummeExklMwSt = (from InvoiceDetail in InvXml.InvDetails.TblInvDetails
                                     where (InvoiceDetail.SpMwSt == mwst)
                                     select InvoiceDetail.SpGesamtBetrag).Sum();
                    if (SummeExklMwSt != 0)
                    {
                        mwstRow = (DsInvoice.TblMwStSummenRow)InvXml.InvDetails.TblMwStSummen.Rows.Add();
                        mwstRow.spMwSt = mwst;
                        mwstRow.spBasisBetrag = SummeExklMwSt.Value;
                        BetragExklMwSt += SummeExklMwSt.Value;
                    }
                }
            }

            UpdateLockedCCText(CC_BetragExcl, BetragExklMwSt.ToString("#,##0.00"));

            //if (Settings.Default.SetVStBerechtigt == true)
            //{
            SummeInklMwSt = (from MwSt in InvXml.InvDetails.TblMwStSummen
                             select MwSt.spGesamtBetrag).Sum();
            SummeMwSt = (from MwSt in InvXml.InvDetails.TblMwStSummen
                         select MwSt.spMwStBetrag).Sum();
            BetragInklMwSt = SummeInklMwSt.Value;
            BetragMwSt = SummeMwSt.Value;
            UpdateLockedCCText(CC_MwSt, BetragMwSt.ToString("#,##0.00"));
            UpdateLockedCCText(CC_Rechnungsbetrag, BetragInklMwSt.ToString("#,##0.00"));

            FillDocTable(this.Tables[docMwstTab],
                InvXml.InvDetails.Tables[InvXml.InvDetails.TblMwStSummen.TableName],
                dtMwStColName, dtMwStColFmt, false, 3);
            //}
            //else
            //{
            //    // UpdateLockedCCText(CC_MwSt, nbsp);
            //    // UpdateLockedCCText(CC_Rechnungsbetrag, nbsp);
            //}


        }
        private void UpdateLockedCCText(Tools.Word.PlainTextContentControl cc, string text)
        {
            cc.LockContents = false;
            if (text == "")
            {
                // cc.Text = "";
                cc.SetPlaceholderText();
            }
            else
            {
                cc.Text = text;
            }
            cc.LockContents = true;
        }
        /// <summary>
        /// Skonto Tabelle aufbauen
        /// </summary>
        private void FillSkontoTabInDoc()
        {
            // spSkontoBetrag berechnen
            foreach (DsInvoice.TblInvSkontoRow sRow in InvXml.InvDetails.TblInvSkonto)
            {
                // Rechnungsbetrag neu in die Tabelle eintragen, damit die Skto Beträge neu berechnet werden
                sRow.spBasisBetrag = BetragInklMwSt;
            }
            FillDocTable(this.Tables[docSkontoTab],
                InvXml.InvDetails.Tables[InvXml.InvDetails.TblInvSkonto.TableName],
                dtSkontoColName,
                dtSkontoColFmt,
                false,
                0);
        }
        /// <summary>
        /// Übertagen aller Tabbellen (Details, MWst und Skonto) in das Word ebDoc
        /// </summary>
        public void UpdateDocDetails()
        {
            // 1. Detailstablle auffüllen
            FillDocTable(this.Tables[docDetailsTab],
                InvXml.InvDetails.Tables[InvXml.InvDetails.TblInvDetails.TableName],
                dtDetailsColName,
                dtDetailsColFmt,
                true,
                0);
            // 2. MwSt Block füllen
            FillMwStTabInDoc();
            // 3. SkontoTabelle füllen
            FillSkontoTabInDoc();



        }
        /// <summary>
        /// Füllt die angegebene Word Tabelle mit den Daten aus der DataTable
        /// </summary>
        /// <param name="docTable">Word Tabelle</param>
        /// <param name="dtTab">DataTable mit den Daten</param>
        /// <param name="colTab">String Tabelle mit den Namen der DataTable Columns in der Reihenfolge wie diese in der Word Tabelle vorkommen</param>
        /// <param name="fmtTab">String Tabelle mit den Format Strings für dezimalwerte</param>
        /// <param name="FirstPos">Soll in der 1. Spalte ein Positionszähler geführt werden</param>
        /// <param name="KeepRows">Anzahl der Zeilnen die am Ende der Tabelle nicht gelöscht werden dürfen</param>
        public void FillDocTable(Word.Table docTable,
            DataTable dtTab,
            string[] colTab,
            string[] fmtTab,
            bool FirstPos,
            int KeepRows)
        {


            UnprotectDoc("FillDocTable");
            // Details in Tabelle einfügen
            // Word.Table docDtTable = this.Tables[docDetailsTab];
            try
            {

                int totRowCnt = docTable.Rows.Count;
                // Alle zeilen nach der 2. Zeile löschen
                for (int i = (totRowCnt - KeepRows); i > 2; i--)
                {
                    docTable.Rows[i].Delete();
                }

                int pos = 0;
                Word.Row cRow = null;
                Word.Cell cCell = null;
                string dtCol = string.Empty;
                string wert = string.Empty;
                int offs = 0;
                object lastRow = new object();

                if (FirstPos == true)
                {
                    offs = 2;
                }
                else
                {
                    offs = 1;
                }
                cRow = docTable.Rows[2];
                for (int i = 1; i < cRow.Cells.Count + 1; i++)
                {
                    cCell = cRow.Cells[i];
                    cCell.Range.Text = "";
                }

                for (int ir = 0; ir < dtTab.Rows.Count; ir++)
                {

                    if (ir == 0)
                    {
                        cRow = docTable.Rows[2];
                    }
                    else
                    {
                        if (KeepRows > 0)
                        {
                            lastRow = cRow;
                            cRow = docTable.Rows.Add(ref lastRow); // neue Tabellenzeile einfügen 
                        }
                        else
                        {
                            cRow = docTable.Rows.Add(ref missing); // neue Tabellenzeile einfügen 
                        }
                    }
                    cRow.Select();
                    for (int i = 1; i < (colTab.Length + offs); i++)
                    {
                        cCell = cRow.Cells[i];
                        pos = cCell.ColumnIndex;
                        if ((pos == 1) && (FirstPos == true)) // Details Positionsnr
                        {
                            cCell.Range.Text = string.Format("{0}", ir + 1);
                        }
                        else
                        {
                            dtCol = colTab[pos - offs];
                            wert = dtTab.Rows[ir][dtCol].ToString();

                            if (fmtTab[pos - offs] != "")
                            {
                                cCell.Range.Text = FormatDecimal(fmtTab[pos - offs], wert);

                            }
                            else
                            {
                                cCell.Range.Text = wert;

                            }
                        }

                    }

                }
            }
            catch (Exception ex)
            {

                throw;
            }
            ProtectDoc("FillDocTable");

        }
        public bool IsMwStInSettings(decimal MwSt)
        {
            bool retVal = true;

            int cnt = 0;
            DataRow[] rows = InvXml.InvDetails.TblMWST.Select("spMwSt='" + MwSt.ToString() + "'");
            cnt = rows.Count();
            if (cnt == 0)
            {
                retVal = false;
            }
            return retVal;
        }

        public bool IsMwStUsedInDetails(decimal MwSt)
        {
            bool retVal = true;

            int cnt = 0;
            DataRow[] rows = InvXml.InvDetails.TblInvDetails.Select("spMwSt='" + MwSt.ToString() + "'");
            cnt = rows.Count();
            if (cnt == 0)
            {
                retVal = false;
            }
            return retVal;
        }
        /// <summary>
        /// Kopiert den Inhalt der hier verwalteten Skonto Tabelle in die des Forms
        /// </summary>
        /// <param name="myDs">Dataset des Forms</param>
        public void FillSkontoTable(DsInvoice myDs)
        {
            CopyTable(InvXml.InvDetails, myDs, myDs.TblInvSkonto.TableName);
        }
        /// <summary>
        /// Kopiert den Inhalt der hier verwalteten Details und MwST Tabelle in die des Forms
        /// </summary>
        /// <param name="myDs"></param>
        public void FillDetailsDataGrid(DsInvoice myDs)
        {
            CopyTable(InvXml.InvDetails, myDs, myDs.TblInvDetails.TableName);
            CopyTable(InvXml.InvDetails, myDs, myDs.TblMWST.TableName);
        }

        /// <summary>
        /// Löscht das aktuelle CustomXMLPart und lädt ein neues
        /// </summary>
        public void LoadTemplateXML(InvoiceXML.TemplateTypes tmplType)
        {

            string xmldata = String.Empty;
            switch (tmplType)
            {
                case InvoiceXML.TemplateTypes.Empty:
                    xmldata = GetFromXMLResource(InvoiceXML.ebInterfaceLeer);
                    break;
                case InvoiceXML.TemplateTypes.FromFile:
                    xmldata = InvXml.LoadXMLTemplate();

                    break;
                default:
                    break;
            }

            if (xmldata != "")
            {
                UnprotectDoc("LoadTemplateXML");
                try
                {
                    Application.ActiveDocument.CustomXMLParts.SelectByID(InvoiceXMLPartID).Delete();

                    InvoiceXMLPartID = null;
                    InvoiceXMLPart = InvXml.AddCustomXmlPart(xmldata);

                    InvXml.InvDetails.LoadMwStTab();
                    bool retVal = InvXml.LoadDetailsTable(InvoiceXMLPart, InvXml.InvDetails);
                    if (retVal == false)
                    {
                        throw (new Exception("Rechnungsdetails konnten nicht geladen werden."));
                    }
                    InvXml.LoadSkontoTable(InvoiceXMLPart, InvXml.InvDetails); // Muss nach InitDoc liegen damit auf die ContentControls zugegriffen werden kann

                    UpdateDocDetails();
                    if (tmplType == InvoiceXML.TemplateTypes.Empty)
                    {
                        Settings2Doc(null);
                    }
                    else
                    {
                        FillDocumentType(CC_InvoiceType, InvoiceXML.xPathDocumentType, GetItemText(InvoiceXML.xPathDocumentType, "Invoice"));
                        FillPlanTextCC(CC_DocumentTitle, InvoiceXML.xPathDocumentTitle, GetItemText(InvoiceXML.xPathDocumentTitle, "Demo Rechnung"));
                        FillCurrency(CC_Currency, InvoiceXML.xPathCurrency, GetItemText(InvoiceXML.xPathCurrency, Settings.Default.setWhrg));
                        FillCountry(CC_RecipientCountry, InvoiceXML.xPathInvRecCountry, GetItemText(InvoiceXML.xPathInvRecCountry, Settings.Default.setLand));
                        FillCountry(CC_BillerCountry, InvoiceXML.xPathBillerCountry, GetItemText(InvoiceXML.xPathBillerCountry, Settings.Default.setLand));
                        string BankLand = XlateTables.FindLand(GetItemText(InvoiceXML.xPathBankLand, XlateTables.FindShortcut(Settings.Default.setBankLandx)));
                        // FillCountry(CC_BankCountry, InvoiceXML.xPathBankLand, BankLand);
                        Globals.ThisDocument.RechnungsdatumInTemplate = Globals.ThisDocument.Rechnungsdatum;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Fehler bei Load Template\r\n" + ex.Message, "XML Vorlage laden", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                b00.Select();
                ProtectDoc("LoadTemplateXML");
            }
            
        }

        public void UID_Bestaetigung()
        {

            FrmUIDBestaetigung UID_Dialog = new FrmUIDBestaetigung();
            UID_Dialog.txUIDReceiver.Text = this.CC_RecipientVATID.Text;
            UID_Dialog.txUIDBiller.Text = this.CC_BillerVATID.Text;
            UID_Dialog.txTeilnehmer.Text = Settings.Default.setTeilnehmer;
            UID_Dialog.txBenutzer.Text = Settings.Default.setBenutzer;
            UID_Dialog.Show();

        }

        private string GetItemText(string xPath, string defaultValue)
        {
            string result = defaultValue;
            Office.CustomXMLNode vNode = InvoiceXMLPart.SelectSingleNode(xPath);
            if (vNode != null)
            {
                result = vNode.Text;
            }
            return result;
        }

        public string GetInvoiceDate()
        {
            string datum = string.Empty;
            Office.CustomXMLNode vnode = InvoiceXMLPart.SelectSingleNode(InvoiceXML.xPathInvDate);
            datum = vnode.Text;
            return datum;
        }
        /// <summary>
        /// Returns the AssemblyDescription Attribute
        /// </summary>
        /// <returns></returns>
        public string GetSVNInfo()
        {
            //string info = string.Empty;
            //Assembly asm = Assembly.GetExecutingAssembly();
            ////info = asm.FullName;
            //string svnInfo = string.Empty;
            //object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyDescriptionAttribute), true);
            //if (attributes.Length > 0)
            //{
            //    AssemblyDescriptionAttribute descriptionAttribute = attributes[0] as AssemblyDescriptionAttribute;
            //    svnInfo = descriptionAttribute.Description;
            //}
            string xmlString = GetFromXMLResource("eRechnung.Version.Version.xml");
            XDocument xdoc = XDocument.Parse(xmlString);

            var tfsInfo = new TfsInfo(xdoc);
            string svnInfo = "ChangeSet: " + tfsInfo.ChangeSetId.ToString() + " Compile: " +
                             tfsInfo.CompileTime.ToString("yyyy.MM.dd HH:mm:ss") + " (" + tfsInfo.CompiledAs + ")";
            return svnInfo;
        }

        /// <summary>
        /// Returns a string containg the XML Data from resource
        /// </summary>
        /// <param name="resourceName"></param>
        /// <returns></returns>
        public string GetFromXMLResource(string resourceName)
        {
            Assembly Asm = Assembly.GetExecutingAssembly();
            Stream St = Asm.GetManifestResourceStream(resourceName);
            StreamReader ResRd = new StreamReader(St);
            if (ResRd != null)
            {
                string xmlData = ResRd.ReadToEnd();
                return (xmlData);
            }

            return (null);
        }

        /// <summary>
        /// Returns the Assmebly Title Attribute
        /// </summary>
        /// <returns></returns>
        public string GetAsmTitle()
        {
            string info = string.Empty;
            Assembly asm = Assembly.GetExecutingAssembly();
            //info = asm.FullName;
            string svnInfo = string.Empty;
            object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), true);
            if (attributes.Length > 0)
            {
                AssemblyTitleAttribute descriptionAttribute = attributes[0] as AssemblyTitleAttribute;
                svnInfo = descriptionAttribute.Title;
            }
            return svnInfo;
        }


        public bool TestEmailRegex(string emailAddress)
        {
            string patternStrict = @"^(([^<>()[\]\\.,;:\s@\""]+"
                  + @"(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@"
                  + @"((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"
                  + @"\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+"
                  + @"[a-zA-Z]{2,}))$";

            Regex reStrict = new Regex(patternStrict);
            bool isStrictMatch = reStrict.IsMatch(emailAddress);
            return isStrictMatch;
        }

        #endregion


        #region ContentControl Events

        private void MyCC_InvoiceDate_Validating(object sender, System.ComponentModel.CancelEventArgs e)
        {

            DateTime rd;
            
            if(DateTime.TryParse(CC_InvoiceDate.Text,out rd)!=true)
            {
                MessageBox.Show("Rechnungsdatum ungültig.");
                e.Cancel = true;
            }
        }


        private void MyCC_InvoiceDate_StoreUpdating(object sender, Microsoft.Office.Tools.Word.ContentControlStoreUpdatingEventArgs e)
        {
            Rechnungsdatum = DateTime.Parse(CC_InvoiceDate.Text);
            DataRow[] skRows = InvXml.InvDetails.TblInvSkonto.Select();
            foreach (DsInvoice.TblInvSkontoRow SkRow in skRows)
            {
                InvXml.InvDetails.TblInvSkonto.UpdateSkontoDatum(SkRow);
            }
            RechnungsdatumInTemplate = Rechnungsdatum;
            // FillSkontoTabInDoc();
            return;
        }
#if ebInterface4Bund
        private void MyCC_ReceipientGLN_Validating(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if ((CC_ReceipientGLN.Text == string.Empty) || (CC_ReceipientGLN.ShowingPlaceholderText == true))
            {
                return;
            }
            GLN_Checker.GLN_ErrorCode cde = CC_ReceipientGLN.Text.IsValidGLN();
            if (cde!=GLN_Checker.GLN_ErrorCode.OK)
            {
                MessageBox.Show("Die GLN des Rechnungsempfängers ins ungültig. ("+cde.GlnErrorToString()+")", "GLN", MessageBoxButtons.OK, MessageBoxIcon.Error);
                e.Cancel = true;
            }

        }

        private void MyCC_BillerGLN_Validating(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if((CC_BillerGLNum.Text==string.Empty)||(CC_BillerGLNum.ShowingPlaceholderText==true))
            {
                return;
            }
            GLN_Checker.GLN_ErrorCode cde = CC_BillerGLNum.Text.IsValidGLN();

            if (cde!=GLN_Checker.GLN_ErrorCode.OK)
            {
                MessageBox.Show("Die GLN des Rechnungsstellers ist ungültig. (" + cde.GlnErrorToString()+")", "GLN", MessageBoxButtons.OK, MessageBoxIcon.Error);
                e.Cancel = true;
            }
        }
#endif
        private void CC_RecipientVATID_Validating(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (CC_RecipientVATID.ShowingPlaceholderText == true)
            {
                MessageBox.Show("Die VAT-ID des Empfängers darf in nicht leer sein. Geben sie ein gültige VAT-ID oder 00000000 ein.");
                e.Cancel = true;
            }
            else
            {
                if (!InvXml.IsValidVATID(CC_RecipientVATID.Text))
                {
                    MessageBox.Show("Die VAT-ID des Empfängers ist nicht plausibel. Geben sie ein gültige VAT-ID oder 00000000 ein.");
                    e.Cancel = true;
                }
            }

        }

        private void CC_DueDate_StoreUpdating(object sender, Microsoft.Office.Tools.Word.ContentControlStoreUpdatingEventArgs e)
        {
            try
            {
                FaelligDatum = DateTime.Parse(e.Content);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Fälligkeitsdatum ungültig.");
            }

        }
        private void CC_Referenz_Validating(object sender, System.ComponentModel.CancelEventArgs e)
        {
            bool error = false;
            if (CC_Referenz.ShowingPlaceholderText == true)
            {
                return;
            }
            // Es wurde etwas eingegeben
            if (CC_Referenz.Text.Length > 12)
            {
                error = true;
            }
            if (!IsValidAlphaNumericString(CC_Referenz.Text))
            {
                error = true;
            }
            if (error)
            {
                MessageBox.Show("Das Feld Referenz muss entweder leer bleiben oder einen numerischen Wert max. 12 Zeichen enthalten.");
            }
            e.Cancel = error;
            return;

        }

        private void MyCC_BillersID_Validating(object sender, System.ComponentModel.CancelEventArgs e)
        {
#if ebInterface4Bund
            PlainTextContentControl ctrl = sender as PlainTextContentControl;
            string liefNr = ctrl.Text;
            if (liefNr.Length != 10)
            {
                e.Cancel = true;
            }
            if (!liefNr.IsAlphaNum())
            {
                e.Cancel = true;
            }
            // e.Cancel = false;
            if (e.Cancel == true)
            {
                MessageBox.Show("Die Lieferantenkennung muss zehn-stellig alphanumerisch sein.", "Lieferantenkennung",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
#endif
        }
        private void MyCC_OrderReference_Entering(object sender, Microsoft.Office.Tools.Word.ContentControlEnteringEventArgs e)
        {
            Globals.Ribbons.ebI_Ribbon.BtnDetails.Enabled = false;
        }

        private void MyCC_OrderReference_Validated(object sender, System.EventArgs e)
        {
            Debug.WriteLine("OrderReference enables Details Button.");
            Globals.Ribbons.ebI_Ribbon.BtnDetails.Enabled = true;
        }

        private void MyCC_OrderReference_Validating(object sender, System.ComponentModel.CancelEventArgs e)
        {
            PlainTextContentControl ctrl = sender as PlainTextContentControl;
            if (ctrl != null)
            {
#if ebInterface4Bund
                string msg = ExtensionMethods.ExtensionMethods.ValidateOrderRefBund(ctrl.Text);
                if (msg != "")
                {
                    MessageBox.Show(msg, "Auftragsreferenz", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    e.Cancel = true;
                }
#endif

            }
        }

        static bool IsValidAlphaNumericString(string strAlphanum)
        {
            Regex pattern = new Regex(@"^\d{1,12}$");
            return pattern.IsMatch(strAlphanum);
        }


        #endregion

        private void ThisDocument_BeforeSave(object sender, Tools.Word.SaveEventArgs e)
        {
            //AppExtensions.eProtectDoc("ThisDocument_BeforeSave", ThisApplication.ActiveDocument, false);
            ProtectDoc("ThisDocument_BeforeSave");
            DocIsBeeingSaved = true;
        }

        private void ThisDocument_SelectionChange(object sender, Tools.Word.SelectionEventArgs e)
        {
            if (DocIsBeeingSaved == true)
            {
                DocIsBeeingSaved = false;
               // AppExtensions.eProtectDoc("ThisDocument_SelectionChange", ThisApplication.ActiveDocument, true);
               // ProtectDoc("ThisDocument_SelectionChange");
            }

        }


        public bool IsBestellBezugValid(string cellValue, out string errorTxt)
        {
            string oId = Globals.ThisDocument.CC_OrderReference.Text;
            // Das funktioniert nur wenn diese Daten erst nach Eingabe der OrderID eingegeben werden können
            errorTxt = "";
            if ((oId.Length == 10) && (oId.IsNumeric()))
            {
                if (cellValue == string.Empty)
                {
                    errorTxt = "Die angegebene Auftragsreferenz erfordert eine Bestellpositionsnummer";

                    return false;
                }
            }

            string bPosNr = cellValue;
            if (bPosNr == String.Empty)
            {
                return true;
            }
            if (!bPosNr.IsNumeric()) // lt. Hr. Helger muss die numerisch sein
            {
                errorTxt = "Die Bestellpositionsnummer ist nicht numerisch";

                return false;
            }
            return true;
        }


 
            public static void LogLine(string line)
        {
#if DEBUG
            using (StreamWriter w = File.AppendText(@"C:\temp\ebInterface.log"))
            {
                string LogLine = string.Format("{0:s} {1}", DateTime.Now, line);
                Debug.WriteLine(LogLine);
                w.WriteLine(LogLine);
                w.Flush();
                w.Close();
            }
#endif
        }
    }
    public static class AppExtensions
    {
        /// <summary> 
        /// Protect a Document 
        /// </summary> 
        /// <param name="objDoc"></param> 
        /// <param name="blnProtect"></param> 
        public static void eProtectDoc(string caller, Word.Document objDoc, bool blnProtect)
        {

            object NoRest = false;
            object Passwod = "AustriaPro";
            Word.WdProtectionType Type = blnProtect ? Word.WdProtectionType.wdAllowOnlyFormFields : Word.WdProtectionType.wdNoProtection;
            object UseIRM = false;
            object EnforceStyleLock = false;
            LogLine("Aufruf: " + caller);
            LogLine("Status=" + objDoc.ProtectionType.ToString() + "; Zielprotection=" + Type.ToString());
            if (objDoc.ProtectionType != Type)
            {
                if (objDoc.ProtectionType != Word.WdProtectionType.wdNoProtection)
                {
                    try
                    {
                        LogLine("Before Document.Unprotect");
                        objDoc.Unprotect(ref Passwod);
                    }
                    catch (Exception ex)
                    {
                        LogLine("Document.Unprotect failed. " + ex.Message);
                    }
                }
                objDoc.Protect(Type, ref NoRest, ref Passwod, ref UseIRM, ref EnforceStyleLock);
            }
            LogLine("Protection set to:" + objDoc.ProtectionType.ToString());
            LogLine("-".PadRight(20, '-'));
        }

        private static void LogLine(string logstr)
        {
            ThisDocument.LogLine(logstr);
        }
    }
}
